<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Support\Str;
use App\Models\Score;
use App\Models\Record;
use App\Models\Ranking;

use  Illuminate\Database\Eloquent\SoftDeletes;

/**
 * App\Models\User
 */
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'phone',
        'password',
        'gender',
        'avatar',
        'api_token'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'api_token',
        'deleted_at'
    ];

    protected $table = 'user';

    use SoftDeletes;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';

    public function updateToken()
    {
        // 随机生成64位字符串
        $this->api_token = hash('sha256', random_bytes(32));
        $this->save();
        return $this->api_token;
    }

    /**
     * 一对一关联个人成绩
     */
    public function score()
    {
        return $this->hasOne(Score::class, 'id')->withDefault();
    }

    /**
     * 一对多关联解谜记录
     */
    public function record()
    {
        return $this->hasMany(Record::class, 'user_id');
    }

    /**
     * 一对一关联排行榜
     */
    public function ranking()
    {
        return $this->hasOne(Ranking::class, 'id')->withDefault();
    }
}
